import os
import sys
import subprocess
import platform
import shutil
import traceback
import re
from PyQt5.QtCore import QThread, pyqtSignal

# 导入分离出去的模块
from .video_operations import VideoOperations
from .frame_operations import FrameOperations
from .crop_operations import CropOperations
from .utils import get_startupinfo

class FFmpegProcessor(QThread, VideoOperations, FrameOperations, CropOperations):
    progress_updated = pyqtSignal(int)
    log_message = pyqtSignal(str)
    process_completed = pyqtSignal(bool, str)
    
    def __init__(self, ffmpeg_path="", hardware_accel="cpu"):
        QThread.__init__(self)
        VideoOperations.__init__(self)
        FrameOperations.__init__(self)
        CropOperations.__init__(self)
        
        self.ffmpeg_path = ffmpeg_path
        # 设置ffprobe路径，通常与ffmpeg在同一目录
        self.ffprobe_path = ffmpeg_path.replace("ffmpeg.exe", "ffprobe.exe") if ffmpeg_path else ""
        self.hardware_accel = hardware_accel
        self.is_running = False
        self.should_stop = False
        self.input_video = ""
        self.output_dir = ""
        self.frames_dir = ""  # 添加frames_dir属性
        self.fps = 30
        self.left_eye_video = ""
        self.right_eye_video = ""
        self.output_video = ""
        self.black_line = False
        self.black_line_width = 20
        self.operation_type = ""  # "extract_frames", "merge_videos", "create_video", "crop_video"
    
    def run(self):
        """运行FFmpeg处理线程"""
        self.is_running = True
        self.should_stop = False
        
        try:
            if self.operation_type == "extract_frames":
                self.extract_frames()
            elif self.operation_type == "create_video":
                self.create_video()
            elif self.operation_type == "merge_videos":
                self.merge_videos()
            elif self.operation_type == "crop_video":
                # 添加裁切视频的操作类型
                success = self.crop_video(
                    self.input_video,
                    self.output_video,
                    self.crop_params,
                    self.hardware_accel != "cpu",
                    self.progress_updated.emit
                )
                self.process_completed.emit(success, "" if success else "视频裁切失败")
            else:
                self.log_message.emit(f"未知操作类型: {self.operation_type}")
                self.process_completed.emit(False, f"未知操作类型: {self.operation_type}")
        except Exception as e:
            self.log_message.emit(f"FFmpeg处理出错: {str(e)}")
            self.log_message.emit(traceback.format_exc())
            self.process_completed.emit(False, f"FFmpeg处理出错: {str(e)}")
        
        self.is_running = False
    
    def stop(self):
        """停止处理"""
        self.should_stop = True
